package com.ssm.sfzy.service.impl;

import com.alibaba.druid.filter.AutoLoad;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.sfzy.entity.Article;
import com.ssm.sfzy.entity.User;
import com.ssm.sfzy.mapper.UserMapper;
import com.ssm.sfzy.service.UserService;
import com.ssm.sfzy.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void add(User user){
        user.setPassword(MD5Util.encode(user.getUsername()+user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public void edit(User user) {
        userMapper.update(user);
    }

    @Override
    public void remove(Integer id) {

    }

    @Override
    public void removeBatch(Integer[] ids) {

    }

    @Override
    public List<User> find(User user) {
        return null;
    }

    @Override
    public Map<String, Object> findPage(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userMapper.select(user);

        PageInfo<User> pageInfo = new PageInfo<>(list);
        Map<String,Object> map = new HashMap<>();
        map.put("list",pageInfo.getList());
        map.put("total",pageInfo.getTotal());

        return map;

    }

    @Override
    public User findById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public User login(String username, String password) {
        System.out.println(username+"1"+password);
        // 登录 --
        // 先根据username来查询，如果查询不到，则用户名不存在
        User user = userMapper.selectByUsername(username);
        System.out.println(user);
        if(user==null){
            return null;    // controller中进行处理即可
        }
        // 如果查询到，则比较密码，如果密码不对，则密码错误
        password = MD5Util.encode(username+password);
        if(!password.equalsIgnoreCase(user.getPassword())){
            return new User();
        }
        return user;  // 账号密码都正确
    }

}
